﻿using AutoMapper;
using B.S.DataBase.MyProject.Domain;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyRead.API.Appicant.Command.Approval;
using B.S.DataBase.MyRead.API.DTOs;
using MediatR;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace B.S.DataBase.MyRead.API.Appicant.CommandHandler.Approval
{
    public class GetLeaveApplicationCommendHandlers : IRequestHandler<GetLeaveApplicationCommends, APIPaging<List<LeaveApplicationsHeadsDtos>>>
    {

        private readonly IBaseRepository<LeaveApplications> leaveapplicationRepository;
        private readonly IBaseRepository<User> userRepository;
        private readonly IBaseRepository<Record> recordRepository;
        private readonly IMapper mapper;

        public GetLeaveApplicationCommendHandlers(IBaseRepository<LeaveApplications> leaveapplicationRepository, IBaseRepository<User> userRepository, IBaseRepository<Record> recordRepository, IMapper mapper)
        {
            this.leaveapplicationRepository = leaveapplicationRepository;
            this.userRepository = userRepository;
            this.recordRepository = recordRepository;
            this.mapper = mapper;
        }




        /// <summary>
        /// 显示申请表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIPaging<List<LeaveApplicationsHeadsDtos>>> Handle(GetLeaveApplicationCommends request, CancellationToken cancellationToken)
        {
            APIPaging<List<LeaveApplicationsHeadsDtos>> result = new APIPaging<List<LeaveApplicationsHeadsDtos>>();
            result.Code = APIEnum.查询成功;
            result.Msg = "查询成功";


            var users = userRepository.GetAllAsync().Result.Where(p => p.UserName.Contains(request.UserName));


            var leaveapplications = leaveapplicationRepository.GetAllAsync().Result;
            var records = recordRepository.GetAllAsync().Result;
            // 获取当前登录用户完整信息
            var currentUser = userRepository.GetAllAsync().Result.FirstOrDefault(p => p.UserName.Contains(request.UserName));



            var list = from a in leaveapplications
                       join b in users on a.DepId equals b.DepId

                       where a.DepId == b.DepId && a.IsDelete == false 
                        
                       select new LeaveApplicationsHeadsDtos
                       {

                           UserId = b.UserId,
                           Heads = b.Heads,
                           UserName = a.UserName,
                           ApplicationId = a.ApplicationId,
                           LeaveType = a.LeaveType,
                           StartTime = a.StartTime,
                           EndTime = a.EndTime,
                           Reason = a.Reason,
                           Status = a.Status,
                           DepId = a.DepId,

                           CreateTime = a.CreateTime,
                           DepheadsName = a.DepheadsName,
                           Leavetime= a.Leavetime,
                           Totalhours = a.Totalhours,

                           Reasonrejection=a.Reasonrejection


                       };
            // 时间段处理
            if (request.StartTime != null && request.EndTime != null)
            {
                list = list.Where(x => x.StartTime >= request.StartTime.Value && x.EndTime <= request.EndTime.Value);
            }



            if (string.IsNullOrEmpty(request.UserName))
            {
                list = list.Where(x => x.UserName.Contains(request.UserName));
            }

            if (request.Status != -1)
            {


                //   bool status=false ? request.Status == 0 : request.Status == 1;
                list = list.Where(x => x.Status == request.Status);
            }
            // 权限过滤逻辑
            if (currentUser.Heads == 0) // 普通员工
            {
                list = list.Where(x =>
                    x.UserName.Contains(currentUser.UserName));
            }
            else
            {

                //非员工
                if (currentUser.Heads == 1)
                {
                    list = list.Where(x =>
                   x.DepId == currentUser.DepId && x.DepheadsName == request.UserName || x.Status==0);
                }
                else
                {
                   
                    list = list.Where(x =>
                   x.DepId == currentUser.DepId&&x.Status!=0 );
                }

            }
            result.TotalCount = list.Count();
            result.TotalPage = (int)(result.TotalCount * 1.0 / request.PageSize);
            list = list.OrderByDescending(p => p.ApplicationId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);

            var data = mapper.Map<List<LeaveApplicationsHeadsDtos>>(list.ToList());


            result.data = data;

            return Task.FromResult(result);
        }


    }
}
